package com.lenovo.smarttraffic.ui.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.database.dao.AccountDatabase;
import com.lenovo.smarttraffic.ui.adapter.BasePagerAdapter;
import com.lenovo.smarttraffic.util.CommonUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyAccountActivity extends BaseActivity {

    private AccountDatabase accountDatabase;
    private SQLiteDatabase db;
    private ContentValues values;
    private Spinner spinner;
    private TextView textView;
    private EditText editText;

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //标题栏
        initToolBar(findViewById(R.id.toolbar), true, getString(R.string.item2));

        //获取选择的选项内容
        spinner = findViewById(R.id.account_spinner);
        //余额TextView
        textView = findViewById(R.id.account_tv_balance_content);
        //获取EditView充值金额
        editText = findViewById(R.id.account_et_recharge);

        //定义数据库的创建
        accountDatabase = new AccountDatabase(this, "AccountInfo.db", null, 1);
        accountDatabase.getWritableDatabase();

        //查询事件
        Button buttonInquire = findViewById(R.id.account_button_inquire);
        buttonInquire.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int balance = balanceInquiry();
                textView.setText(balance + "元");
            }
        });

        //如果db数据库中的Balance表为空的话就添加初始化数据
        initAccount();
        //充值事件
        Button buttonRecharge = findViewById(R.id.account_button_recharge);
        buttonRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //获取当前系统时间
                SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd HH:mm"); //设置日期格式
                String date = df.format(new Date());
                //添加数据
                db = accountDatabase.getWritableDatabase();
                values = new ContentValues();
                values.put("car", Integer.parseInt((String) spinner.getSelectedItem()));
                values.put("recharge", Integer.parseInt(editText.getText().toString()));
                values.put("admin", "admin");
                values.put("time", date);
                db.insert("Account", null, values); //插入数据
                values.clear();
                //更改余额
                textView.setText(balanceInquiry() + "元");
            }
        });

        textView.setText(balanceInquiry() + "元");

    }
    //初始化数据库信息
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initAccount() {
        db = accountDatabase.getWritableDatabase();
        if (db.rawQuery("select * from Balance", null).getCount() == 0) {
            //如果db数据库中的Balance表为空，就初始化数据
            values = new ContentValues();
            values.put("car", 1);
            values.put("balance", 80);
            db.insert("Balance", null, values); //插入数据
            values.clear();
            values.put("car", 2);
            values.put("balance", 50);
            db.insert("Balance", null, values); //插入数据
            values.clear();
            values.put("car", 3);
            values.put("balance", 150);
            db.insert("Balance", null, values); //插入数据
            values.clear();
        }
    }

    //查询余额
    public int balanceInquiry() {
        int spinnerData = Integer.parseInt((String) spinner.getSelectedItem());
        int balanceBal = 0;
        int balanceAcc = 0;
        int balance = 0;
        db = accountDatabase.getWritableDatabase();
        //查询Balance表中的有关数据
        Cursor cursorBal = db.query("Balance", null, null, null, null, null, null);
        if (cursorBal.moveToFirst()) {
            do {
                if (spinnerData == cursorBal.getInt(cursorBal.getColumnIndex("car"))) {
                    balanceBal = cursorBal.getInt(cursorBal.getColumnIndex("balance"));
                }
            } while (cursorBal.moveToNext());
        }
        cursorBal.close();
        //查询Account表中有没有充值记录
        if (db.rawQuery("select * from Account", null).getCount() != 0) {
            Cursor cursorAcc = db.query("Account", null, null, null, null, null, null);
            if (cursorAcc.moveToFirst()) {
                do {
                    if (spinnerData == cursorAcc.getInt(cursorAcc.getColumnIndex("car"))) {
                        balanceAcc = cursorAcc.getInt(cursorAcc.getColumnIndex("recharge"));
                        balance = balance + balanceAcc;
                    }
                } while (cursorAcc.moveToNext());
            }
        } else {
            balance = 0;
        }
        return balanceBal + balance;
    }

    //重写这个方法，设置布局文件
    @Override
    protected int getLayout() {
        return R.layout.activity_my_account;
    }

    //数据请求
    private void sendRequestWithOk() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("CarId","2")
                            .add("UserName","user1")
                            .build();
                    Request request = new Request.Builder()
                            .url("http://192.168.1.102:8088/transportservice/action/GetCarAccountBalance.do")
                            .post(requestBody)
                            .build();
                    Response response = okHttpClient.newCall(request).execute();
                    String responseData = response.body().string();
                    //数据解析
                    parseJsonWithGson(responseData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //使用Gson解析Json数据
    private void parseJsonWithGson(String jsonData) {
        Gson gson = new Gson();

    }


}
